package com.storydo.file.share.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.storydo.file.share.config.FileConfiguration;
import com.storydo.file.share.rest.AuthController;

/**   
* @Title: AuthInterceptor.java 
* @Description: TODO
* @author : Storydo
* @date: 2019年7月9日 上午11:20:55 
* @version:V1.0 
* Copyright 悦享互联 2016 All right reserved.
* Modification  History:
* Version       Date          Author          Description
* ----------------------------------------------------------------------------
*  1.0         2019年7月9日        Storydo              TODO
*/


public class AuthInterceptor extends HandlerInterceptorAdapter {

	private Logger log = LoggerFactory.getLogger(AuthInterceptor.class);
	
	@Autowired
	FileConfiguration fileConfig;
	
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String uri = request.getRequestURI();
		log.debug(" request uri  == " + uri);
		if ("/".equals(uri) || (uri.equals("/auth") && !fileConfig.isAuth())) {
			// 首页重定向
			response.sendRedirect("/file/home");
			return false;
		}
		if (uri.equals("/auth") && request.getSession().getAttribute(AuthController.AUTH_KEY) != null) {
			response.sendRedirect("/file/home");
			return false;
		}
		// 安全验证
		if (fileConfig.isAuth() && !uri.startsWith("/auth")) {
			HttpSession session = request.getSession();
			if (session.getAttribute(AuthController.AUTH_KEY) == null) {
				response.sendRedirect("/auth");
				return false;
			}
		}
		return super.preHandle(request, response, handler);
	}
	
}
